package efe.bean;

import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.Serializable;
import javax.swing.JOptionPane;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */



/**
 *
 * @author root
 */
public class EfeEditorField extends javax.swing.JTextField implements Serializable {

    private boolean inited = false;

    protected EfeValue value;

    /**
     * Get the value of value
     *
     * @return the value of value
     */
    public EfeValue getValue() {
        return value;
    }

    /**
     * Set the value of value
     *
     * @param value new value of value
     */
    public void setValue(EfeValue value) {
        this.value = value;
        update();
    }

    protected String labelText;

    /**
     * Get the value of label
     *
     * @return the value of label
     */
    public String getLabelText() {
        return labelText;
    }

    /**
     * Set the value of label
     *
     * @param label new value of label
     */
    public void setLabelText(String label) {
        this.labelText = label;
    }

    /**
     * Dodaje zdarzenie dwukliku do siebie.
     */
    public EfeEditorField() {
        super();
        setEditable(false);
        //setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));
        setHorizontalAlignment(javax.swing.JTextField.CENTER);
        addMouseListener(new MouseListener() {
            public void mouseClicked(MouseEvent me) {
                if (me.getClickCount() != 2) return;
                if (value != null) {
                    setText(value.display());
                }
                else {
                    setText("");
                }
                setEditable(true);
                inited = true;
            }
            public void mousePressed(MouseEvent me) {
            }
            public void mouseReleased(MouseEvent me) {
            }
            public void mouseEntered(MouseEvent me) {
            }
            public void mouseExited(MouseEvent me) {
            }
        });
        addFocusListener(new FocusListener() {
            public void focusGained(FocusEvent fe) {}
            public void focusLost(FocusEvent fe) {
                if (!inited) return;
                setEditable(false);
                if (!value.validate(getText())) {
                    JOptionPane.showMessageDialog(null, value.getMessage());
                }
                setText(labelText + " = " + value.display());
            }
        });
    }

    public void update() { setText(labelText + " = " + value.display()); }

}

